package com.chatmusicstatus.accounts;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.preference.Preference;
import com.chatmusicstatus.R;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;

public class addAdv extends PreferenceActivity {
    
    AccountSQLiteHelper accHelper;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        addPreferencesFromResource(R.xml.createaccountadv);
        accHelper = new AccountSQLiteHelper(this);
        findPreference("save").setOnPreferenceClickListener(new OnPreferenceClickListener() {

            public boolean onPreferenceClick(Preference prfrnc) {
                SQLiteDatabase db = accHelper.getWritableDatabase();
                ContentValues accInfo = new ContentValues();
                accInfo.put(AccountSQLiteHelper.ANAME, ((EditTextPreference)findPreference("accname")).getText());
                accInfo.put(AccountSQLiteHelper.UNAME, ((EditTextPreference)findPreference("uname")).getText());
                accInfo.put(AccountSQLiteHelper.PASS, ((EditTextPreference)findPreference("pass")).getText());
                accInfo.put(AccountSQLiteHelper.SERVER, ((EditTextPreference)findPreference("server")).getText());
                accInfo.put(AccountSQLiteHelper.PORT, ((EditTextPreference)findPreference("port")).getText());
                accInfo.put(AccountSQLiteHelper.SERVICE, ((EditTextPreference)findPreference("service")).getText());
                if(((CheckBoxPreference)findPreference("enable")).isChecked())
                    accInfo.put(AccountSQLiteHelper.ENABLE, 1);
                else
                    accInfo.put(AccountSQLiteHelper.ENABLE, 0);
                accInfo.put(AccountSQLiteHelper.MESSAGE, "");
                accInfo.put(AccountSQLiteHelper.UTUNE, 2);
                try
                {
                    if(db.insertOrThrow(AccountSQLiteHelper.TABLE, null, accInfo)==-1)
                    {
                        //an error occured
                        Toast.makeText(addAdv.this, R.string.acccreateerror, Toast.LENGTH_LONG).show();
                        return false;
                    }
                }
                catch(SQLiteException ex)
                {
                    Toast.makeText(addAdv.this, R.string.acccreateerror, Toast.LENGTH_LONG).show();
                    return false;
                }
                setResult(1);
                finish();
                return true;
            }
        });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        accHelper.close();
  }
}
